package com.mapfinal.mapcache.online;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;

import com.jfinal.core.Controller;
import com.mapfinal.mapcache.MapCachePersistence;
import com.mapfinal.mapcache.MapServer;
import com.mapfinal.mapcache.MapServerManager;
import com.mapfinal.mapcache.ParameterConversion;
import com.mapfinal.mapcache.utils.HttpKit;
import com.mapfinal.server.service.tile.TileHttpResponseRender;
import com.mapfinal.server.service.tile.TileParam;

public class OnlineMapServer implements MapServer {

	private ParameterConversion parameterConversion;
	private MapCachePersistence mapCache;
	private Map<String, String> header = new HashMap<String, String>();
	private Map<String, String> layerUrls = new HashMap<String, String>();
	
	public OnlineMapServer(ParameterConversion parameterConversion, MapCachePersistence mapCache) {
		// TODO Auto-generated constructor stub
		this.parameterConversion = parameterConversion;
		this.setMapCache(mapCache);
		this.header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
	}
	
	@Override
	public ParameterConversion getParameterConversion() {
		// TODO Auto-generated method stub
		if(parameterConversion==null) {
			parameterConversion = new WmtsParameterConversion();
		}
		return parameterConversion;
	}
	
	@Override
	public MapCachePersistence getMapCache() {
		mapCache = mapCache==null ? MapServerManager.me().getMapCache() : mapCache;
		return mapCache;
	}

	@Override
	public void renderTileImage(TileParam tile, Controller controller) {
		// TODO Auto-generated method stub
		boolean flag = getMapCache().renderFromCache(tile, controller);
		if(flag) {
			return;
		}
		
		String layer = tile.getLayer();
		String url = layerUrls.get(layer);
		String s = controller.getPara("s");
		String curl = url.replace("{s}", s);
		curl = curl.replace("{z}", tile.getZoom().toString());
		curl = curl.replace("{x}", tile.getX().toString());
		curl = curl.replace("{y}", tile.getY().toString());
		System.out.println("map: " + curl);
		try {
			HttpResponse result = HttpKit.keepAlive().httpGet(curl, null, header);
			mapCache.inputTileToCache(tile, result);
			controller.render(new TileHttpResponseRender(curl, result, controller.getRequest()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void setParameterConversion(ParameterConversion parameterConversion) {
		// TODO Auto-generated method stub
		this.parameterConversion = parameterConversion;
	}

	@Override
	public void setMapCache(MapCachePersistence mapCache) {
		this.mapCache = mapCache;
	}

}
